﻿using System.Net;
using System.Net.Sockets;
using System.Text;

/// <summary>
/// TPC服务器用于检测用户状态和任务分发操作
/// </summary>

public class TCPServer
{
    private int port = 8844;

    private Socket server;
    private Thread thread;
    private List<Socket> clients = new List<Socket>();

    public TCPServer()
    {
        StartServer();
    }

    public void StartServer()
    {
        server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint point = new IPEndPoint(IPAddress.Any, port);
        server.Bind(point);
        // 打印服务器地址和端口
        Console.WriteLine("TCP服务器已启动，地址: " + point.Address + "，端口: " + point.Port);

        server.Listen(5);
        thread = new Thread(StartAccept);
        thread.Start();
    }

    // 用户连接
    private void StartAccept()
    {
        while (true)
        {
            var client = server.Accept();
            if (!clients.Contains(client))
            {
                clients.Add(client);
                Console.WriteLine("新客户端连接到了服务器，客户端地址: " + client.RemoteEndPoint);
            }
        }
    }

    // 广播消息给所有客户端
    public void BroadcastMessage(string message)
    {
        foreach (Socket client in clients)
        {
            SendMessage(client, message);
        }
    }

    // 接收客户端消息并打印
    private void ReceiveMessage(Socket client)
    {
        byte[] buffer = new byte[1024];
        int bytesRead = client.Receive(buffer);
        string receivedMessage = Encoding.ASCII.GetString(buffer, 0, bytesRead);
        Console.WriteLine("收到来自客户端的消息：" + receivedMessage);
    }

    // 主动向指定客户端发送消息
    public void SendMessage(Socket client, string message)
    {
        byte[] data = Encoding.ASCII.GetBytes(message);
        client.Send(data);
    }
}